<template>
  <HeaderTitle title="编辑工单流程图"></HeaderTitle>
  <div class="editArticleTablePage">
    <div class="row wrap masterRouteBox items-center">
      <div class="col-6 col-sm-3">
        <span>编号: {{ serial }}</span>
      </div>
      <div class="col-6 col-sm-3">
        <span>设计编号: {{ design }}</span>
      </div>
      <div class="col-6 col-sm-3">
        <span>模号: {{ model }}</span>
      </div>
      <div class="col-6 col-sm-3">
        <span>成色: {{ gold }}</span>
      </div>
      <div class="col-12 col-sm-6">
        <span>FG Article: {{ article }}</span>
      </div>
      <div class="col-12 col-sm-6">
        <span>是否1种镶工:</span>
        <q-btn-dropdown
          split
          class="glossy isOneJobBox"
          color="deep-purple-5"
          :label="isOneJob"
        >
          <q-list>
            <q-item clickable v-close-popup @click="isOneJob = '是'">
              <q-item-section> 是 </q-item-section>
            </q-item>

            <q-item clickable v-close-popup @click="isOneJob = '否'">
              <q-item-section> 否 </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </div>
    </div>

    <div class="standardRoutingTbBox">
      <q-table
        class="srTable"
        flat
        bordered
        table-header-class="bg-grey-4"
        :rows="editrows"
        :columns="srtcolumns"
        row-key="stepNo"
      >
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="stepNo" :props="props">
              <q-icon
                name="fa-regular fa-square-minus"
                class="removeSVG"
                @click="removeRow(props.rowIndex)"
              />
              {{ props.row.stepNo }}
              <q-icon
                name="fa-solid fa-arrow-up"
                class="upDownSVG"
                @click="rowUp(props.rowIndex)"
              />
              <q-icon
                name="fa-solid fa-arrow-down"
                class="upDownSVG"
                @click="rowDown(props.rowIndex)"
              />
            </q-td>
            <q-td key="routeName" :props="props">
              {{ props.row.routeName }}
              <q-popup-edit
                v-model="props.row.routeName"
                auto-save
                v-slot="scope"
              >
                <q-select
                  v-model="scope.value"
                  :options="routeNameOpt"
                  :option-value="'pk'"
                  :option-label="'name'"
                  emit-value
                  map-options
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="qty" :props="props">
              {{ props.row.qty }}
              <q-popup-edit
                v-model="props.row.qty"
                title="Update qty"
                auto-save
                v-slot="scope"
              >
                <q-input
                  type="number"
                  v-model="scope.value"
                  dense
                  autofocus
                  @keyup.enter="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="difficulty" :props="props">
              <div class="text-pre-wrap">{{ props.row.difficulty }}</div>
              <q-popup-edit
                v-model="props.row.difficulty"
                auto-save
                v-slot="scope"
              >
                <q-select
                  v-model="scope.value"
                  :options="difficultyOpt"
                  :option-value="'pk'"
                  :option-label="'name'"
                  emit-value
                  map-options
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="psName" :props="props">
              <div class="text-pre-wrap">{{ props.row.routeName === '镶石' ? props.row.psName : '不适用' }}</div>
              <q-popup-edit
                v-model="props.row.psName"
                auto-save
                v-slot="scope"
                :disable="props.row.routeName !== '镶石'"
              >
                <q-select
                  v-model="scope.value"
                  :options="psNameOpt"
                  :option-value="'pk'"
                  :option-label="'name'"
                  emit-value
                  map-options
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="ssName" :props="props">
              <div class="text-pre-wrap">{{ props.row.routeName === '镶石' ? props.row.ssName : '不适用'}}</div>
              <q-popup-edit
                v-model="props.row.ssName"
                auto-save
                v-slot="scope"
                :disable="props.row.routeName !== '镶石'"
              >
                <q-select
                  v-model="scope.value"
                  :options="ssNameOpt"
                  :option-value="'pk'"
                  :option-label="'name'"
                  emit-value
                  map-options
                  @change="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="consumePercent" :props="props">
              {{ props.row.consumePercent }}
              <q-popup-edit
                v-model="props.row.consumePercent"
                auto-save
                title="Update consumePercent"
                v-slot="scope"
              >
                <q-input type="number" v-model="scope.value" dense autofocus />
              </q-popup-edit>
            </q-td>
            <q-td key="workfee" :props="props">
              {{ props.row.workfee }}
              <q-popup-edit
                v-model="props.row.workfee"
                auto-save
                title="Update workfee"
                v-slot="scope"
              >
                <q-input type="number" v-model="scope.value" dense autofocus />
              </q-popup-edit>
            </q-td>
            <q-td key="addRow" :props="props">
              <q-icon
                name="fa-regular fa-square-plus"
                class="addSVG"
                @click="addRow(props.rowIndex)"
              />
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </div>
    <div class="btnBox">
      <q-btn color="grey-8" class="cancelBtn" label="取消" @click="cancel()">
      </q-btn>
      <q-btn
        color="blue-8"
        class="saveBtn"
        label="储存工序流程"
        @click="save()"
      >
        <q-icon name="fa-solid fa-floppy-disk" class="saveSVG" />
      </q-btn>
    </div>
  </div>
</template>

<script setup>
import HeaderTitle from "src/components/HeaderTitle.vue";
import { ref, toRaw } from "vue";
import { useRouter } from "vue-router";
import { useUploadWoStore } from "src/stores/modules/uploadWoFlowStore";
import { useQuasar } from "quasar";

const $router = useRouter();
const useUploadWo = useUploadWoStore();

const $q = useQuasar()

// const routeNameOpt = ['倒模', '执模', '出水', '执模', '镶石', '执边', '电金', 'PF']
// const difficultyOpt = ['1 很低', '2 低', '3 中', '4 高', '5 很高']
// const psNameOpt = ['59 其他 闸钉+小虎 白钻/宝石', '56 抹镶 红/蓝/半宝石/绿加力', '44 迫镶 小迫镶']
// const ssNameOpt = ['56 抹镶 红/蓝/半宝石/绿加力', '53 抹镶 钻石', '38 爪镶 小爪镶圆爪']

const routeNameOpt = Array.from(useUploadWo.flow_list).map((item) => ({
  pk: item.chinese_name,
  name: item.chinese_name,
}));
const difficultyOpt = Array.from(useUploadWo.difficulty_list).map((item) => ({
  pk: item.name,
  name: item.name,
}));
const psNameOpt = Array.from(useUploadWo.stone_mount_list).map((item) => ({
  pk: item.name,
  name: item.name,
}));
const ssNameOpt = Array.from(useUploadWo.stone_mount_list).map((item) => ({
  pk: item.name,
  name: item.name,
}));

// items
const master_id = ref(null)
const serial = ref(null);
const design = ref(null);
const model = ref(null);
const gold = ref(null);
const article = ref(null);
const isOneJob = ref("否");

let srtcolumns = [];
let srtrows = [];
let editrows = [];

srtcolumns = [
  {
    name: "stepNo",
    required: true,
    label: "项目",
    align: "center",
    field: (row) => row.stepNo,
    format: (val) => `${val}`,
    sortable: false,
  },
  {
    name: "routeName",
    required: true,
    align: "center",
    label: "Routing名称",
    field: "routeName",
    sortable: false,
  },
  {
    name: "qty",
    required: true,
    align: "center",
    label: "分件数量",
    field: "qty",
    sortable: false,
  },
  {
    name: "difficulty",
    align: "center",
    label: "难易程度",
    field: "difficulty",
    sortable: false,
  },
  {
    name: "psName",
    align: "center",
    label: "镶法技术(主)",
    field: "psName",
    sortable: false,
  },
  {
    name: "ssName",
    align: "center",
    label: "镶法技术(次)",
    field: "ssName",
    sortable: false,
  },
  {
    name: "consumePercent",
    align: "center",
    label: "给耗(%)",
    field: "consumePercent",
    sortable: false,
  },
  {
    name: "workfee",
    align: "center",
    label: "工人工费(元)",
    field: "workfee",
    sortable: false,
  },
  {
    name: "addRow",
    align: "center",
    label: "新增步骤",
    field: "addRow",
    sortable: false,
  },
];

const init = () => {
  // get FG Article + details
  const fgItem = useUploadWo.getFGArticle(+props.fgArticle_id);
  console.log("fgItem: ", fgItem);
  // initialize variables
  if (fgItem) {
    master_id.value = fgItem.master_id;
    serial.value = fgItem.serial;
    design.value = fgItem.design;
    model.value = fgItem.mould;
    gold.value = fgItem.gold;
    article.value = fgItem.article;
    isOneJob.value = fgItem.is_one_inlay;
  }

  // init item
  srtrows = fgItem.item;
};

const props = defineProps({
  fgArticle_id: { type: String, required: true },
});
console.log("props", props);
console.log("props.fgArticle: ", props.fgArticle_id);
if (props.fgArticle_id) {
  init();
}

editrows = ref([]);
editrows.value = [...JSON.parse(JSON.stringify(srtrows))];

// Function: Remove row
const removeRow = (rowIndex) => {
  editrows.value = [
    ...editrows.value.slice(0, rowIndex),
    ...editrows.value.slice(rowIndex + 1),
  ];
  for (let i = rowIndex; i < editrows.value.length; i++) {
    editrows.value[i].stepNo = "步骤 " + (i + 1);
  }
};

// Function: Add row
const addRow = (rowIndex) => {
  const newRowIndex = rowIndex + 1;
  const newRowStepNo = newRowIndex + 1;
  const newRow = {
    stepNo: "步骤 " + newRowStepNo,
    routeName: null,
    qty: null,
    difficulty: null,
    psName: null,
    ssName: null,
    consumePercent: null,
    workfee: null,
  };

  editrows.value = [
    ...editrows.value.slice(0, rowIndex + 1),
    newRow,
    ...editrows.value.slice(rowIndex + 1),
  ];
  for (let i = newRowIndex + 1; i < editrows.value.length; i++) {
    editrows.value[i].stepNo = "步骤 " + (i + 1);
  }
};

// Function: rowUp
const rowUp = (rowIndex) => {
  if (rowIndex > 0) {
    const preIndex = rowIndex - 1;
    editrows.value[rowIndex].stepNo = "步骤 " + (preIndex + 1);
    editrows.value[preIndex].stepNo = "步骤 " + (rowIndex + 1);
    const temprev = editrows.value[preIndex];
    editrows.value[preIndex] = editrows.value[rowIndex];
    editrows.value[rowIndex] = temprev;
  } else {
    // console.log('already on the top')
  }
};

// Function: rowDown
const rowDown = (rowIndex) => {
  if (rowIndex < editrows.value.length - 1) {
    const postIndex = rowIndex + 1;

    editrows.value[rowIndex].stepNo = "步骤 " + (postIndex + 1);
    editrows.value[postIndex].stepNo = "步骤 " + (rowIndex + 1);

    const tempost = editrows.value[postIndex];

    editrows.value[postIndex] = editrows.value[rowIndex];
    editrows.value[rowIndex] = tempost;
  } else {
    // console.log('already the bottom la')
  }
};

// Function: cancel
const cancel = () => {
  console.log("cancel");
  editrows.value = [...JSON.parse(JSON.stringify(srtrows))];
  $router.back();
};

// Function: save
const save = async () => {
  const check_flow = editrows.value.find(i=>i.routeName==null)
  if (check_flow){
    $q.notify({
      type: "negative",
      textColor: "white",
      message: "Routing名称不能空白 !",
      timeout: 2000,
      position: "center",
    });
    return
  }
  srtrows = [...JSON.parse(JSON.stringify(editrows.value))];
  console.log("save content: ", srtrows);
  console.log("save");
  const res = await useUploadWo.saveFGArticle(
    master_id.value,
    isOneJob.value,
    srtrows
  );
  console.log("res", res);
  if (res) {
    $router.back();
  } else {
    // error alert
    console.log("error");
  }
};
</script>

<style lang="scss" scoped>
.editArticleTablePage {
  width: 95%;
  margin-left: auto;
  margin-right: auto;
  font-size: 1.2rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }
  .masterRouteBox {
    background-color: rgba(255, 255, 255, 0.884);
    margin-top: 10px;
    border-radius: 10px;
    padding: 10px 10px 10px 10px;
    color: #451a8b;
    font-weight: bold;
    .col-auto {
      margin-right: 10px;
    }
    .isOneJobBox {
      margin-left: 5px;
    }
  }
  .standardRoutingTbBox {
    background-color: rgba(255, 255, 255, 0.884);
    margin-top: 10px;
    border-radius: 10px;
    padding: 10px 10px 10px 10px;
    .removeSVG {
      color: red;
      margin-right: 10px;
    }
    .addSVG {
      color: #4436d0;
    }

    .upDownSVG {
      color: #838383;
      font-size: 1rem;
    }

    .removeSVG,
    .addSVG {
      font-size: 1.5rem;
    }
  }
  .btnBox {
    margin-top: 10px;
    text-align: center;
    .saveBtn {
      margin-bottom: 10px;
      .saveSVG {
        font-size: 1rem;
        margin-left: 5px;
      }
    }
    .cancelBtn {
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }
}
</style>
